package com.maybach.workflow.common.api;

import com.maybach.util.AssertUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by houenxun on 15/10/22.
 * 和IIntercepter类似，但通过流程定义文件植入到流程中
 */
public class FlowHandlerFactory {
    static  Logger logger = LoggerFactory.getLogger(FlowHandlerFactory.class);
    private static Map<String, IFlowHandler> handlerMap = new HashMap<String, IFlowHandler>();

    public static IFlowHandler getHandler(String name){
        return handlerMap.get(name);
    }


    public static List<IFlowHandler> getHandlers(String [] names){
        List<IFlowHandler> handlers = new ArrayList<IFlowHandler> ();
        for(String name : names){
            IFlowHandler handler = handlerMap.get(name);
            if(null != handler){
                handlers.add(handler);
            }
        }
        return handlers;
    }

    public static void register(String key, IFlowHandler handler){
        AssertUtil.notNull(handler, "handler");
        AssertUtil.notBlank(key, "key");
        if(handlerMap.containsKey(key)){
            logger.error("重复注册 key={}, handler={}",key, handler.getClass());
            return ;
        }
        handlerMap.put(key, handler);

    }

    public static void handle(String  names, WorkFlowContext context){
        if(StringUtils.isNotBlank(names)){
            for(IFlowHandler handler : getHandlers(names.split(","))){
                handler.handle(context);
            }
        }
    }




    public void setHandlerMap(Map<String, IFlowHandler> hMap) {
        handlerMap = hMap;
    }

}
